# -*- coding:utf-8 -*-
import numpy as np 
from  builtins import range
from functools import reduce
import aod.comLibs as cm
import os.path
import scipy.io
import time

'''
    Transmit simulation results into matlab compatible data
'''

def transmitSatMeanDataToReadble(filefolder,satIndices):
    for satnum in satIndices:
        distfname = filefolder+'/sat'+str(satnum)+'_'+'.txt'
        distf =  open(distfname,'w')
        fileIndex =1 
        while True:
            fname  = filefolder+'/sat'+str(satnum)+'_'+str(fileIndex)+'.npz'
            if os.path.isfile(fname):
                    tmpData = np.load(fname)
                    timeTags  = tmpData['timeTag']
                    kineStateMeans = tmpData['kineStateMeans']
                    row = kineStateMeans.shape[0]
                    col = kineStateMeans.shape[1]
                    m  = np.zeros((row+1,col))
                    m[0,:] = timeTags.reshape((1,col))
                    m[1:row+1,:] = kineStateMeans
                    strWrite = ''
                    for i in range(0,m.shape[1]):
                        linedata = m[:,i].tolist()
                        strWrite = strWrite + ' '.join(str(metadata) for metadata in linedata) + '\n'
                    distf.write(strWrite)
            else:
                break
            fileIndex += 1
        distf. close()

def dumpSatREcordtoMatlab(filefolder,satIndices):
    for satnum in satIndices:
        distfname = filefolder+'/sat'+str(satnum)+'.mat'
        distf =  open(distfname,'w')
        fileIndex =1 
        initialNeed  =  True
        while True:
            fname  = filefolder+'/sat'+str(satnum)+'_'+str(fileIndex)+'.npz'
            if os.path.isfile(fname):
                    tmpData = np.load(fname)
                    if initialNeed:
                        initialNeed = False
                        timeTags    =    tmpData['timeTag']
                        kineStateMeans = tmpData['kineStateMeans']
                        kineStateCovs =  tmpData['kineStateCovs']
                        timeDiffMeans =  tmpData['timeDiffMeans']
                        timeDiffCovs  = tmpData['timeDiffCovs']
                    else:
                        timeTags         =     np.append(timeTags,tmpData['timeTag'])
                        kineStateMeans   =     np.concatenate((kineStateMeans,tmpData['kineStateMeans']),1)
                        kineStateCovs    =     np.concatenate((kineStateCovs,tmpData['kineStateCovs']),2)
                        timeDiffMeans   =     np.concatenate((timeDiffMeans,tmpData['timeDiffMeans']))
                        timeDiffCovs   =     np.concatenate((timeDiffCovs,tmpData['timeDiffCovs']))
            else:
                break
            fileIndex += 1
        scipy.io.savemat(distfname, {'timeTags':timeTags, 'kineStateMeans':kineStateMeans,'kineStateCovs':kineStateCovs,'timeDiffMeans':timeDiffMeans,'timeDiffCovs':timeDiffCovs})
        distf. close() 

if __name__ =="__main__":
    #satrecordFileprefix = './data/simResults/progressbackV2/'+'sat'
    # satrecordFileprefixs = ['./data/simResults/satPropError_0/'+'sat',
    #                         './data/simResults/satPropError_3/'+'sat',
    #                         './data/simResults/satPropError_4/'+'sat',
    #                         './data/simResults/satPropError_5/'+'sat',
    #                         './data/simResults/satPropError_6/'+'sat',
    #                         './data/simResults/satPropError_8/'+'sat'
    #                        ]
    # # satrecordFileprefixs = ['./data/simResults/satPropError_8/'+'sat']
    # satrecordFileprefixs = []
    # for experiment in range(1,100):
    #     satrecordFileprefixs.append('./data/simResults/satPropError_mento_8_exp'+str(experiment)+'/sat')


    # #                        ]
    # # merge the result
    # # satrecordFileprefixs = ['./data/simResults/satPropError_0/'+'sat',          './data/simResults/satPropError_4/'+'sat','./data/simResults/satPropError_6/'+'sat']

    # # satrecordFileprefixs =[]
    # for satrecordFileprefix in satrecordFileprefixs:
    #     for satnum  in range(1,2):

    #         fileIndex  = 1 
    #         initialNeed  =  True
    #         while True:
    #             fname  = satrecordFileprefix+str(satnum)+'_'+str(fileIndex)+'.npz'
    #             if os.path.isfile(fname):
    #                 #print 'there is a file'
    #                 tmpData = np.load(fname)
    #                 if initialNeed:
    #                     initialNeed = False
    #                     timeTags    =    tmpData['timeTag']
    #                     kineStateMeans = tmpData['kineStateMeans']
    #                     kineStateCovs =  tmpData['kineStateCovs']
    #                 else:
    #                     timeTags    =     np.append(timeTags,tmpData['timeTag'])
    #                     kineStateMeans    =     np.concatenate((kineStateMeans,tmpData['kineStateMeans']),1)
    #                     kineStateCovs    =     np.concatenate((kineStateCovs,tmpData['kineStateCovs']),2)
    #             else:
    #                 break
    #             fileIndex += 1

    #         print timeTags.shape
    #         print kineStateMeans.shape
    #         print kineStateCovs.shape
    #         scipy.io.savemat(satrecordFileprefix+str(satnum)+'.mat', {'timeTags':timeTags, 'kineStateMeans':kineStateMeans,'kineStateCovs':kineStateCovs})
    import  simSettings as settings

    filefolder = settings.SIMU_SIM_DATA_FOLDER+'parallel_noNoiseModel_Re0_eRe8/'
    satIndices = list(range(1,25))
    dumpSatREcordtoMatlab(filefolder,satIndices)